# -*- coding = utf-8 -*-
# @Time : 2022/11/30 19:20
# @Author : GHHHHHHHHH
# @File : Token.py
# @Software : PyCharm
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, BadSignature
from config import TokenConfig
from enums.TokenEnum import TokenEnum


def generate_token(api_users):
    s = Serializer(TokenConfig.SECRET_KEY, expires_in=TokenConfig.EXPIRATION)
    token = s.dumps({'id': api_users}).decode('ascii')
    return token, TokenConfig.EXPIRATION


def verify_auth_token(request):
    tokenEnum = TokenEnum()
    if request.method == 'OPTIONS':
        return
    token = request.headers.get('token')
    if token is None:
        return {"STATUS": "No Token."}, tokenEnum.NOT_FOUND
    s = Serializer(TokenConfig.SECRET_KEY)
    try:
        s.loads(token)
    except SignatureExpired:
        return {"STATUS": "Token expired."}, tokenEnum.OUT_OF_DATE
    except BadSignature:
        return {"STATUS": "Unknown Token."}, tokenEnum.UNKNOWN_TOKEN
